package com.alogic.es.xscript.search;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsArray;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.doc.json.JsonArray;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * query by terms
 *
 * @since 1.6.13.9 [20200824 duanyy]
 */
public class EsTerms extends AbstractLogiclet {
    protected String $field;
    protected String $value;
    protected String $boost = "1.0";
    protected String delimeter = ",";

    public EsTerms(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);
        $field = PropertiesConstants.getRaw(p,"field",$field);
        $value = PropertiesConstants.getRaw(p,"value",$value);
        $boost = PropertiesConstants.getRaw(p,"boost",$boost);
        delimeter = PropertiesConstants.getString(p,"delimeter",delimeter);
    }

    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        String field = PropertiesConstants.transform(ctx,$field,"");
        String value = PropertiesConstants.transform(ctx,$value,"");
        if (StringUtils.isNotEmpty(field) && StringUtils.isNotEmpty(value)) {
            XsObject query = current.getObjectChild("terms", true);
            query.addProperty("boost", PropertiesConstants.transform(ctx,$boost,1.0f));
            XsArray array = query.getArrayChild(field,true);
            if (array instanceof JsonArray){
                JsonArray jsonArray = (JsonArray)array;
                @SuppressWarnings("unchecked")
                List<Object> content = (List<Object>)jsonArray.getContent();
                String [] values = value.split(delimeter);
                for (String v:values){
                    content.add(v);
                }
            }
        }
    }
}